package com.white.loglib;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * Created by ytf on 2021/5/23 023.
 * Description:
 */

public class LogProtocolBean {

    public int type;
    public String content;

    private ByteBuffer buffer;
    private byte[] frame;

    private static final byte[] HEAD = {(byte) 0xAA, (byte) 0xAA};

    public LogProtocolBean(int type, String content) {
        this.type = type;
        this.content = content;
        if(type != -1){
            buffer = ByteBuffer.allocate(8);
            buffer.putLong(System.currentTimeMillis());

            byte tp = (byte) (0xFF & type);
            byte[] time = buffer.array();
            byte[] msg = content.getBytes(StandardCharsets.UTF_8);

            short msgLen = (short) (0xFFFF & msg.length);
            byte[] lenBuf = new byte[2];
            lenBuf[0] = (byte) ((msgLen >> 8) & 0xFF);
            lenBuf[1] = (byte) (msgLen & 0x00FF);

            int size = 2 + 1 + 8 + msgLen + 2;
            frame = new byte[size];
            System.arraycopy(HEAD, 0, frame, 0, 2);
            frame[2] = tp;
            System.arraycopy(time, 0, frame, 3, 8);
            System.arraycopy(lenBuf, 0, frame, 11, 2);
            System.arraycopy(msg, 0, frame, 13, msgLen);
        }
    }

    public boolean isEOF(){
        return type == -1;
    }

    public byte[] getBytes(){
        return frame;
    }
}
